import React from 'react';
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  TouchableOpacity,
} from 'react-native';
import {Actions} from 'react-native-router-flux';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import api from '../../common/api';
import CommonStyle from '../../common/styles';

export default class List extends React.Component {
  state = {
    params: [],
    loading: false,
    page: 1,
    forums: [],
  }

  componentDidMount() {
    this.setState({
      loading: true,
    }, () => {
      console.log("going to fetchForums");
      this.fetchForums();
    })
  }

  fetchForums() {
    try {
      api.listForum("taxonomy_key=" + this.props.router_params.taxonomy.key).then(res => {
        this.setState({
          forums: res.data.list,
          loading: false,
        })
      });
    } catch (error) {
      console.error(error);
    }
   
    
  }

  onRefresh() {
    console.log("onRefresh");
    if (this.state.loading) {
      console.log("loading");
      return;
    }
    this.setState({
      loading: true,
      page: 1,
    }, () => {
      this.fetchForums();
    })
  }

  gotoTopicScreen(item) {
    Actions.TopicScreen({
      "router_params": {
        "come_from": "来自版块分类筛选", 
        "forum": item
      }, 
      "title": item.name + "版块",
    });
  }

  renderItem({item, index}) {
    return (
      <TouchableOpacity style={[styles.itemWrap]} onPress={() => this.gotoTopicScreen(item)}>
        <Text>{item.name}</Text>
        <Icon name="chevron-right" size={16} />
      </TouchableOpacity>
    )
  }

  itemSeparator = () => {
    return (
      <View style={styles.itemSeparator}></View>
    )
  }

  render() {
    return (
      <View style={CommonStyles.container}>
        <FlatList
          data={this.state.forums}
          renderItem={(item) => this.renderItem(item)}
          refreshing={this.state.loading}
          onRefresh={() => this.onRefresh()}
          ItemSeparatorComponent={this.itemSeparator}
        />
      </View>
    );
  }

}

const styles = StyleSheet.create({
  forumItem: {
    justifyContent: "space-between",
  },
  pageTitle: {
    display: "flex",
    flexDirection: "row",
    justifyContent: "center",
    marginTop: 10,
    marginBottom: 10
  },
  pagetTitleLeft: {
    alignSelf: "flex-start"
  },
  itemWrap: {
    marginTop: 10,
    marginBottom: 10,
    display: "flex",
    flexDirection: "row",
    justifyContent: "space-between"
  },
  itemSeparator: {
    display: "flex",
    height: 1,
    backgroundColor: "#ddd"
  },
  arrow: {
    position: "absolute",
    right: 0
  }

})

